#pragma once

#include <unistd.h>
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include "Common.hpp"

//创建一个命名管道，进程结束时自动关闭该管道
class Init
{
public:
    Init()
    {
        int n = mkfifo(gpipe_file.c_str(), gmode);
        if(n < 0)
        {
            std::cerr << "mkfifo error" << std::endl;
            return;
        }
        std::cout << "mkfifo success" << std::endl;
        //sleep(10);
    }
    ~Init()
    {
        int n = unlink(gpipe_file.c_str());
        if(n < 0)
        {
            std::cerr << "unlink error" << std::endl;
            return;
        }
        std::cout << "unlink success" << std::endl;
    }
};

Init init;

class Server
{
public:
    Server():_fd(gdefaultfd)
    {}
    bool OpenPipeForRead()
    {
        _fd = OpenPipe(OpenForRead);
        if(_fd < 0) return false;
        return true;
    }
    int ReceivePipe(std::string *out)
    {
        char buffer[gsize];
        ssize_t n = ::read(_fd, buffer, sizeof(buffer)-1);
        if(n > 0)
        {
            buffer[n] = 0;
            *out = buffer;
        }
        return n;
    }
    void ClosePipe()
    {
        ClosePipeHelper(_fd);
    }
    ~Server()
    {}
private:
    int _fd;
};